package com.stylefeng.guns.modular.huamao.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.huamao.dao.SktOrderRefundsMapper;
import com.stylefeng.guns.modular.huamao.dao.SktOrdersMapper;
import com.stylefeng.guns.modular.huamao.dao.SpecCatsMapper;
import com.stylefeng.guns.modular.huamao.dao.SpecItemsMapper;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.service.*;


import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 线上商城订单表 服务实现类
 * </p>
 *
 * @author caody123
 * @since 2018-04-14
 */
@Service
@Log
public class SktOrdersServiceImpl extends ServiceImpl<SktOrdersMapper, SktOrders> implements ISktOrdersService {

	@Autowired
	SktOrdersMapper som;
	@Autowired
	IUsersAddressService usersAddressService;
	@Autowired
	private IGoodsService getGoodsService;
	@Autowired
	private ISktOrderGoodsService sktOrderGoodsService;
	@Autowired
	private IGoodsService goodsService;
	@Autowired
	private IMessagesService messagesService;
	@Autowired
	private SpecItemsMapper specItemsMapper;
	@Autowired
	private SpecCatsMapper specCatsMapper;
	@Autowired
	private IGoodsSpecsService goodsSpecsService;
	@Autowired
	private SktOrderRefundsMapper sktOrderRefundsMapper;





	@Override
	public Object selectOrderShops(SktOrdersList sktOrdersList) {
		// TODO Auto-generated method stub
		return som.selectOrderShops(sktOrdersList);
	}

	@Override
	public Object selectOrderScore(Map<String,Object> param) {
		// TODO Auto-generated method stub
		return som.selectOrderScore(param);
	}

	@Override
	public Object selectOrderGoods(Integer sktOrdersId) {
		// TODO Auto-generated method stub
		List<Map<String,Object>> list = som.selectOrderGoods(sktOrdersId);
		for(Map<String,Object>  map:list){
			Integer isSpec = Integer.parseInt(map.get("isSpec").toString());
			List<Map<String,Object>> mapList = new ArrayList<Map<String, Object>>();
			if (isSpec == 1){
				Integer goodsSpecId  = Integer.parseInt(map.get("goodsSpecId").toString());
				GoodsSpecs  goodsSpecs =  new GoodsSpecs();

				goodsSpecs = goodsSpecsService.selectById(goodsSpecId);

				String specIds  = goodsSpecs.getSpecIds();
				map.put("goodsPrice",goodsSpecs.getSpecPrice());


				if(specIds != null){
					String[] parts = specIds.toString().split(":");

					for (int i = 0 ; i <parts.length ; i++ ) {
						Map<String,Object> objectMap = new HashMap<String, Object>();
						Integer itemId = Integer.parseInt(parts[i]);
						SpecItems specItems = new SpecItems();
						specItems = specItemsMapper.selectById(itemId);
						objectMap.put("itemName",specItems.getItemName());
						SpecCats specCats =  new SpecCats();
						specCats = specCatsMapper.selectById(specItems.getCatId());
						objectMap.put("catName",specCats.getCatName());
						mapList.add(objectMap);
					}
				}
				map.put("specList",mapList);

			}

			map.put("specList",mapList);
			map.put("freight","");
		}
		return  list;
	}

	@Override
	public Object selectOrderGoodsParameter(Map<String, Object> param) {
		// TODO Auto-generated method stub
		return som.selectOrderGoodsParameter(param);
	}

	@Override
	public int selectCount() {
		// TODO Auto-generated method stub
		return som.selectCount();
	}

	@Override
	public int selectOrderTotal() {
		// TODO Auto-generated method stub
		return som.selectOrderTotal();
	}

    @Override
    public List<Map<String, Object>> selectUserOrders(SktOrdersList sktOrdersList) {

		if ("-3".equals(sktOrdersList.getsOrderStatus())){
			List<Map<String, Object>> listmaps = sktOrderRefundsMapper.selectOrderRefunds(sktOrdersList);
			return  listmaps;
		}else {
			List<Map<String, Object>> list  = som.selectUserOrders(sktOrdersList);
			return list;
		}
    }

    /**
     * 购物车结算时生成的订单
     */
	@Override
	public int produceOrders(SktOrders sktOrders) {
		// TODO Auto-generated method stub
		return som.produceOrders(sktOrders);
	}

	/**
	 * 查询用户地址
	 */
	@Override
	public List<Map<String, Object>> selectAddressByUserid(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return som.selectAddressByUserid(map);
	}
	/**
	 * 重新设置默认地址
	 * @param map
	 * @return
	 */
	@Transactional
	@Override
	public Boolean changeIsDefault(Map<String, Object> map){
		
		try {
			int userId =  (int) map.get("userId");
			int addressId =  (int) map.get("addressId");
			
			/**
			 * 根据userid清空默认地址
			 */
			UsersAddress usersAddress = new UsersAddress();
			usersAddress.setUserId(userId);
			EntityWrapper<UsersAddress> ew=new EntityWrapper<UsersAddress>(usersAddress);
			List<UsersAddress> list = usersAddressService.selectList(ew);
			for(UsersAddress ua:list){
				ua.setIsDefault(0);
			}
			usersAddressService.updateBatchById(list);
			//usersAddressService.update(usersAddress, ew);
			/**
			 * 根据addressId设置默认地址
			 */
			UsersAddress usersAddress1 = new UsersAddress();
			usersAddress1.setAddressId(addressId);
			usersAddress1.setUserId(userId);
			usersAddress1.setIsDefault(1);
			
			usersAddressService.updateById(usersAddress1);
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return false;
		}
		
	}
	
	/**
	 * 添加收货地址
	 * @param map
	 * @return
	 */
	@Transactional
	@Override
	public Boolean addAddress(UsersAddress usersAddress){
		try {
			usersAddressService.insert(usersAddress);
			if(1==usersAddress.getIsDefault()){
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("userId", usersAddress.getUserId());
				map.put("addressId", usersAddress.getAddressId());
				this.changeIsDefault(map);
			}
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return false;
		}
		
	}

	@Override
	public Map<String, Object> selectUserOrdersInfo(SktOrdersList sktOrdersList) {
		Map<String,Object> map = som.selectUserOrdersInfo(sktOrdersList);
		return map;
	}

	/**
	 * 提交订单
	 * @param sktOrdersIds
	 * @param sktOrders
	 * @return
	 */
	@Override
	public Boolean submitOrder(List<Map<String, Object>> listMap,SktOrders sktOrders) {

		List<SktOrders> sktOrdersList = new ArrayList<SktOrders>();

		try {
			for (Map<String, Object> map : listMap) {
				/**
				 * 必须新建一个对象，否则add加入的是同一个对象
				 */
				SktOrders rsktOrders = new SktOrders();
				Integer sktOrdersId = Integer.parseInt(map.get("sktOrdersId").toString());
				String orderRemarks = map.get("orderRemarks").toString();
				BigDecimal deliverMoney= new BigDecimal(map.get("deliverMoney").toString());
				/**
				 * 封装要更新的订单队列
				 */
				rsktOrders.setOrderId(sktOrdersId);
				rsktOrders.setOrderRemarks(orderRemarks);
				rsktOrders.setOrderStatus(sktOrders.getOrderStatus());
				rsktOrders.setPayType(sktOrders.getPayType());
				rsktOrders.setAreaId(sktOrders.getAreaId());
				rsktOrders.setAreaIdPath(sktOrders.getAreaIdPath());
				rsktOrders.setUserName(sktOrders.getUserName());
                rsktOrders.setDeliverMoney(deliverMoney);
				rsktOrders.setUserAddress(sktOrders.getUserAddress());
				rsktOrders.setUserPhone(sktOrders.getUserPhone());
				rsktOrders.setInvoiceClient(sktOrders.getInvoiceClient());
				rsktOrders.setIsInvoice(sktOrders.getIsInvoice());
				rsktOrders.setDataFlag(sktOrders.getDataFlag());
				rsktOrders.setCreateTime(sktOrders.getCreateTime());

				sktOrdersList.add(rsktOrders);
				/**
				 *减去物品的数量，在redis中处理
				 */
//				SktOrderGoods sktOrderGoods = new SktOrderGoods();
//				sktOrderGoods.setOrderId(sktOrdersId);
//				EntityWrapper<SktOrderGoods> ew = new EntityWrapper<SktOrderGoods>(sktOrderGoods);
//				List<SktOrderGoods> sktOrderGoodsList = sktOrderGoodsService.selectList(ew);
//				for (SktOrderGoods sktOrderGoods1 : sktOrderGoodsList) {
//					int goodsnum = sktOrderGoods1.getGoodsNum();
//					Goods goods = goodsService.selectById(sktOrderGoods1.getGoodsId());
//					int surplus = goods.getGoodsStock().intValue() - goodsnum;
//					goods.setGoodsId(sktOrderGoods1.getGoodsId());
//					goods.setGoodsStock(surplus);
//					/**
//					 * 如果库存到达预警线发送给店铺发送消息
//					 */
//					if (goods.getWarnStock().intValue() > surplus) {
//
//					}
//					goodsService.updateById(goods);
//				}

			}
			/**
			 * 批量更新订单的内容
			 */
			List<SktOrders> sktOrdersList2 = new ArrayList<SktOrders>();
			for (SktOrders s :
					sktOrdersList) {
			    SktOrderGoods sktOrderGoods = new SktOrderGoods();
                sktOrderGoods.setOrderId(s.getOrderId());
                EntityWrapper<SktOrderGoods> entityWrapper = new EntityWrapper<SktOrderGoods>(sktOrderGoods);
                List<SktOrderGoods> list=  sktOrderGoodsService.selectList(entityWrapper);
                BigDecimal  num = new BigDecimal("0");
                int payScore=0;
                for(SktOrderGoods sktOrderGoods1:list){
                    num =  num.add(sktOrderGoods1.getGoodsPrice().multiply(new BigDecimal(sktOrderGoods1.getGoodsNum())));
					payScore=payScore+sktOrderGoods1.getPayScore();
                }
				SktOrders sktOrders1 = this.selectById(s.getOrderId());
				sktOrders1.setPayScore(payScore);
				sktOrders1.setDeliverMoney(s.getDeliverMoney());
                sktOrders1.setGoodsMoney(num);
				sktOrders1.setTotalMoney(num.add(s.getDeliverMoney()));
				sktOrders1.setAreaId(s.getAreaId());
				sktOrders1.setAreaIdPath(s.getAreaIdPath());
				sktOrders1.setUserName(s.getUserName());
				sktOrders1.setUserAddress(s.getUserAddress());
				sktOrders1.setUserPhone(s.getUserPhone());
				sktOrders1.setIsInvoice(sktOrders1.getIsInvoice());
				sktOrders1.setOrderRemarks(s.getOrderRemarks());
				if(s.getInvoiceClient() != null && s.getInvoiceClient() != ""){
				sktOrders1.setInvoiceClient(s.getInvoiceClient());
				}
				sktOrdersList2.add(sktOrders1);
			}
			System.out.println(sktOrdersList2);
			this.updateBatchById(sktOrdersList2);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 添加快递单号
	 * @param sktOrders

	 * @return
	 */
	@Override
	@Transactional
	public JSONObject addExpressNo(SktOrders sktOrders ){
		JSONObject json=new JSONObject();
		try{
			SktOrders sktOrders1=som.selectById(sktOrders.getOrderId());
			sktOrders1.setOrderStatus(1);
			sktOrders1.setDeliveryTime(new Date());
			sktOrders1.setExpressId(sktOrders.getExpressId());
			sktOrders1.setExpressNo(sktOrders.getExpressNo());
			som.updateById(sktOrders1);
			List<Integer> usersIds=new ArrayList<Integer>();
			usersIds.add(sktOrders1.getUserId());
			messagesService.addMessages(1,1,usersIds,"您的订单【"+sktOrders1.getOrderNo() +"】已发货啦，快递号为："+sktOrders1.getExpressNo()+"，请做好收货准备哦~",null);
			json.put("code","01");
			json.put("msg","添加快递单号成功");
		}catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			json.put("code","00");
			json.put("msg","添加快递单号失败");
		}
		return json;
	}

	@Override
	public List<Map<String,Object>> appFindAllOrders(Integer shopId,String orderStatus) {
		Map<String,Object> para = new HashMap<String,Object>();
		para.put("shopId",shopId);
		para.put("orderStatus",orderStatus);
		//查询所有订单
		List<Map<String, Object>> list = som.appFindAllOrders(para);
		//查询订单下的所有商品
		for (Map<String, Object> map:
			list ) {
			Integer orderId = (Integer)map.get("orderId");
			List<Map<String,Object>> list2 = sktOrderGoodsService.appFindGoodById(orderId);
			map.put("goods",list2);
			//订单总商品数量
			Integer num = 0;
			if(list2 != null && list2.size() >0){
				for (Map<String,Object> map2:
					 list2) {
					Integer num2 = (Integer)map2.get("goodsNum");
					num += (Integer)map2.get("goodsNum");
				}
			}
			map.put("countGoodsNum",num);
		}
		return list;
	}

	@Override
	public Integer appUpdateStatus(Map<String, Object> map) {
		return som.appUpdateStatus(map);
	}

	@Override
	public Map<String, Object> appFindOrdersDetailed(String orderNo) {
		Map<String, Object> map = som.appFindOrdersDetailed(orderNo);
		Integer orderId = (Integer)map.get("orderId");
		List<Map<String,Object>> list = sktOrderGoodsService.appFindGoodById(orderId);
		map.put("list",list);
		return map;
	}

	@Override
	public List<Map<String, Object>> appFindToBeEvaluatedOrders(Map<String, Object> map) {
		//查询所有订单
		List<Map<String, Object>> list = som.appFindToBeEvaluatedOrders(map);
		//查询订单下的所有商品
		for (Map<String, Object> map1:
				list ) {
			Integer orderId = (Integer)map1.get("orderId");
			List<Map<String,Object>> list2 = sktOrderGoodsService.appFindGoodById(orderId);
			map1.put("goods",list2);
			//订单总商品数量
			Integer num = 0;
			if(list2 != null && list2.size() >0){
				for (Map<String,Object> map2:
						list2) {
					Integer num2 = (Integer)map2.get("goodsNum");
					num += (Integer)map2.get("goodsNum");
				}
			}
			map1.put("countGoodsNum",num);
		}
		return list;
	}

	@Override
	public List<Map<String, Object>> appFindrefundOrder(int shopId, Integer refundStatus) {
		Map<String,Integer> map = new HashMap<String,Integer>();
		map.put("shopId",shopId);
		map.put("refundStatus",refundStatus);
		List<Map<String, Object>> list = som.appFindrefundOrder(map);
		//查询订单下的所有商品
		for (Map<String, Object> map1:
				list ) {
			Integer orderId = (Integer)map1.get("orderId");
			List<Map<String,Object>> list2 = sktOrderGoodsService.appFindGoodById(orderId);
			map1.put("goods",list2);
			//订单总商品数量
			Integer num = 0;
			if(list2 != null && list2.size() >0){
				for (Map<String,Object> map2:
						list2) {
					Integer num2 = (Integer)map2.get("goodsNum");
					num += (Integer)map2.get("goodsNum");
				}
			}
			map1.put("countGoodsNum",num);
		}
		return list;
	}
	@Override
	public Integer orderBatch(){
		log.info("dadasdasdasdasdas");
		return  som.orderBatch();
		//return  0;
	};
	@Override
	public void updateOrderStatus(Map map) {
		som.updateOrderStatus(map);
	}
}
